<template>
  <div class="footer">
    <div
      class="driving-control-panel control-panel-box std-border"
      v-for="(panel, idx) of localParams"
      :key="idx"
    >
      <div class="panel-header std-border">
        <div>{{ panel.name }}:</div>
        <div
          :class="{ 'blink-text': panel.logoInfo === '暂停标志' }"
          class="panel-header-logo"
        >
          {{ panel.logoInfo }}
        </div>
      </div>
      <div class="panel-content std-border">
        <Form class="left-form" :label-width="50" label-position="left">
          <FormItem :label="panel.params.actualStation.label">
            <InputNumber
              v-model="panel.params.actualStation.value"
              :min="0"
              :max="999"
              @on-blur="handleBlur('actualStation', idx)"
            />
          </FormItem>

          <FormItem :label="panel.params.preStation.label">
            <InputNumber
              v-model="panel.params.preStation.value"
              :min="0"
              :max="999"
              @on-blur="handleBlur('preStation', idx)"
            />
          </FormItem>

          <FormItem :label="panel.params.workpiece.label">
            <InputNumber
              v-model="panel.params.workpiece.value"
              :min="0"
              :max="32000"
              @on-blur="handleBlur('workpiece', idx)"
            />
          </FormItem>

          <FormItem :label="panel.params.targetPosition.label">
            <InputNumber
              v-model="panel.params.targetPosition.value"
              :min="0"
              :max="999"
              @on-blur="handleBlur('targetPosition', idx)"
            />
          </FormItem>

          <FormItem class="groupId" :label="panel.params.groupId.label">
            <InputNumber
              v-model="panel.params.groupId.value"
              :min="0"
              :max="2147483600"
              @on-blur="handleBlur('groupId', idx)"
            />
          </FormItem>
        </Form>

        <div class="right-buttons">
          <Button
            v-for="btn in panel.controlBtns"
            :key="btn.type"
            :type="btn.btnType"
            :loading="btn.loading"
            @click="handleControl(btn.type, idx)"
          >
            {{ btn.label }}
          </Button>
        </div>
      </div>
      <div
        class="panel-footer std-border"
        v-if="panel.promptMessage !== '提示消息'"
      >
        {{ panel.params.errorSlotNum.value }} {{ panel.promptMessage }}
        {{ panel.params.overflowValue.value }}
      </div>
    </div>

    <div class="auto-button-panel control-panel-box std-border">
      <div class="std-title std-border">自动启动</div>
      <div class="auto-buttons std-two-columns std-border">
        <Button
          v-for="(btn, idx) of autoButtonPanel"
          :class="{ 'hidden-button': !btn.show }"
          :key="idx"
          size="large"
          :type="btn.btnType"
          @click="panelBtnClick(btn)"
          >{{ btn.title }}</Button
        >
      </div>
      <div class="start-btn">
        <Button type="primary" @click="handleAutoStart">启动默认产线</Button>
      </div>
    </div>

    <div class="device-jump-panel control-panel-box std-border">
      <div
        v-for="device in devices"
        :key="device.id"
        class="device-card"
        :style="{ background: device.bgColor }"
        @click="navigateTo(device.funName)"
      >
        <i :class="`wy-icon ${device.icon}`"></i>
        <span class="device-name">{{ device.name }}</span>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Tsrv, T_srv, ifs, ts, vue, I_cmd, T_cmd, N_cStph, devicePanels } from './config';

@T_srv.comp
export default class ControlPanels extends vue {
  @T_srv.inject({ default: () => { } }) addTabFunc;

  /* 行车控制面板信息 */
  @T_srv.prop({
    required: true,
    type: Array<N_cStph.craneControlConfig>
  })
  craneControlConfig: N_cStph.craneControlConfig[];

  /* 行车自动面板信息 */
  @T_srv.prop({
    required: true,
    type: Array<N_cStph.autoBtn>
  })
  autoButtonPanel: N_cStph.autoBtn[];

  @T_srv.watch('craneControlConfig', {deep: true})
  updateParams(){
    this.localParams = Tsrv.utils.clone(this.craneControlConfig, true);
  }


  private navConfigData: any = this.$store.getters.SysInfo.navs;

  /* 启动按钮定时器 */
  private timer: any;

  private localParams: N_cStph.craneControlConfig[] = [];

  private devicePanels = devicePanels();

  private devices = [];

  created() {
    this.localParams = Tsrv.utils.clone(this.craneControlConfig, true);
  }

  mounted() {
    this.init();
  }

  destroyed() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  }

  private init() {
    // 通过菜单权限过滤设备面板

    const navTitles = new Set();

    for (const nav of this.navConfigData) {
      if (['system', 'test', 'scada'].includes(nav.title)) continue;

      nav.menus.forEach(menu => {
        menu.groupMembers.forEach(member => {
          this.collectTitles(member, navTitles);
        });
      });
    }

    this.devices = this.devicePanels.filter(device =>
      device.funName && navTitles.has(device.funName)
    );
  }


  // 收集navs中所有title值的函数
  private collectTitles(navItem, titles = new Set()) {
    if (navItem.title) {
      titles.add(navItem.title);
    }
    if (navItem.children) {
      navItem.children.forEach(child => this.collectTitles(child, titles));
    }
    return titles;
  }


  /* 行车按钮点击 */
  private handleControl(type: string, index: number) {
    const control = this.craneControlConfig[index].controlBtns.find(c => c.type === type);
    if (control) {
      control.loading = true;
      setTimeout(() => {
        control.loading = false;
        const data = [{ ecDetCode: control.code, value: 'true' }];
        Tsrv.writePlcData(data).then(success => {
          if (success) {
            this.$Message.success(`${control.label}成功`);
          }
        });
      }, 300);
    }
  }

  /* 面板按钮点击 */
  private panelBtnClick(btn: N_cStph.autoBtn) {
    if (btn.key !== 'specifyRunningSteps') {


      const data = [{ ecDetCode: btn.ecCode, value: 'true' }];
      Tsrv.writePlcData(data).then(success => {
        if (success) {
          this.$Message.success(`${btn.title}成功`);
        }
      });
    } else {
      this.$emit('show-modal', 'specifyRunningSteps');
    }
  }

  /* 输入框失去焦点 */
  private handleBlur(field: string, index: number) {
    const info = this.craneControlConfig[index].params[field];
    const data = [{ ecDetCode: info.code, value: info.value }];
    Tsrv.writePlcData(data).then(_ => {
        Tsrv.readPlcData([info.code]).then(res => {
          if (typeof res === 'boolean') return;
          info.value = res[info.code].v;
        }
        )
    })
  }

  private navigateTo(funName: string) {
    this.$store
      .dispatch('getLayoutConfigAsync', {
        funid: null,
        field: funName,
        type: 'custom'
      })
      .then((res: any) => {
        if (res) {
          this.addTabFunc(funName);
        }
      });
  }

  // 启动默认产线
  private handleAutoStart() {
    // 获取默认产线的相关信息
    const filter = { is_default: 1 };
    this.doLoadData('produc_line_mgmt', filter).then(([b, res, rows, msg]) => {
      if (!b) {
        this.$msg(msg);
      }else {
        const defaultLine = rows[0];
        this.$store.dispatch('getLayoutConfigAsync', {
          funid: null,
          field: 'cPLDetails',
          type: 'component'
        })
        .then((r: any) => {
            this.addTabFunc('cPLDetails').then((resp: any) => {
              // 发送产线启动事件
              setTimeout(() => {
                this.$bus.$emit('MY_RUN_PRODUC_LINE', defaultLine);
              }, 0);
            })
          }
        );
      }
    }
    )
  }

  public doLoadData(tableName: string, filter = {}) {
    const gpd = new ts.T_getPartDataArg();
    gpd.setFilter(filter);
    gpd.setFunName(tableName);
    gpd.setTableName(tableName);
    gpd.setDbType(Tsrv.globalVar.dbType.MYSQL);
    gpd.setLang(this.$i18n.locale);
    gpd.setPage(1, 999);
    gpd.setRule({} as ifs.I_rule);

    return Tsrv.getData(gpd);
  }
}
</script>

<style lang="scss" scoped>
.footer {
  height: 32%;
  display: grid;
  grid-template-columns: 1.5fr 1.5fr 1fr 2fr;
  column-gap: 5px;

  .driving-control-panel {
    .panel-header {
      width: 100%;
      height: 10%;
      display: flex;
      flex-direction: row;
      align-items: center;
      div:first-child {
        height: 100%;
        background-color: #d6ffff;
        color: #098b88;
        font-weight: 600;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 0 10px;
        margin-right: 2px;
      }
      div:last-child {
        flex: 1;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        font-weight: 500;
        font-size: 12px;
      }
    }
    .panel-content {
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      width: 100%;
      height: 80%;
      padding: 10px;
      overflow: hidden;
      overflow-y: auto;
      text-align: center;
      font-size: 12px;

      .left-form {
        display: grid;
        grid-template-columns: 1fr 1fr;
        column-gap: 16px;
        height: 60%;
        .groupId {
          grid-column: span 2;
        }
      }

      .right-buttons {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 16px;
        height: 40%;
        button {
          height: 100%;
        }
      }
    }
    .panel-footer {
      width: 100%;
      height: 10%;
      font-weight: 600;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #d6ffff;
    }
  }

  .auto-button-panel {
    width: 100%;
    .auto-buttons {
      height: 65%;
      button {
        height: 80%;
        // background-color: #098b88;
        color: white;
        font-size: 14px;
        border-radius: 8px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-5px);
          box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }
      }
    }
    .start-btn {
      width: 100%;
      height: 20%;
      button {
        width: 100%;
        height: 100%;
        background-color: #098b88;
        color: white;
        font-size: 14px;
        border-radius: 8px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-5px);
          box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }
      }
    }
  }

  .device-jump-panel {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    // grid-auto-rows: minmax(100px, 1fr);
    gap: 16px;
    padding: 10px;
    height: 100%;

    .device-card {
      // aspect-ratio: 1/1;
      border-radius: 8px;
      height: 90%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: all 0.3s ease;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
      }

      .wy-icon {
        font-size: 20px;
        margin-bottom: 5px;
        color: white;
      }

      .device-name {
        color: white;
        font-size: 14px;
        font-weight: 500;
        text-align: center;
        padding: 0 5px;
        text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
      }
    }
  }
}
::v-deep .ivu-form-item {
  margin-bottom: 12px;
  .ivu-input-number {
    width: 100%;
    height: 22px;
    line-height: 22px;
  }
  .ivu-form-item-label {
    padding: 6px 12px 6px 0;
  }
  .ivu-form-item-content {
    line-height: 22px;
  }
  .ivu-input-number-input-wrap {
    height: 22px;
    input {
      height: 22px;
      line-height: 22px;
    }
  }
  .ivu-input-number-handler {
    height: 11px; // 上下按钮高度
  }
}

.control-panel-box {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 5px;
  box-shadow: 2px 4px 2px -2px var(--globalSearch-input-bg-color),
    -2px -4px 15px -2px var(--globalSearch-input-bg-color);
}

.std-border {
  border: 1px solid #eee;
  border-radius: 5px;
  box-shadow: 2px 4px 2px -2px var(--globalSearch-input-bg-color),
    -2px -4px 15px -2px var(--globalSearch-input-bg-color);
}

.std-two-columns {
  width: 100%;
  display: grid;
  grid-template-columns: 1fr 1fr;
  column-gap: 5px;
}

.std-title {
  width: 100%;
  height: 15%;
  font-weight: 600;
  font-size: 14px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.hidden-button {
  visibility: hidden;
}

@keyframes blink {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}

.blink-text {
  animation: blink 1s infinite;
  color: #ffad33;
}
</style>
